<?php
/**
 * 任务协同管理
 */
namespace app\miniprogram\task;

use app\common\service\Order as OrderService;
use app\system\model\SystemUser as UserModel;
use app\common\service\WechatUser;
use app\common\service\TProject as TProjectService;
use app\common\service\TTask as TTaskService;
use app\common\model\SystemAnnex as AnnexModel;
use \app\common\service\SystemUser as SystemUserService;
class TaskApi extends AuthLogin
{

    public function initialize() {
         parent::initialize();
    }

    /**
     * 项目列表
     * sparkguo 2021.09.22
     */
    public function projectList(){
        $tProjectService=new TProjectService();
        $keyword    = $this->request->param('keyword/s');
        $where      = $data = [];
        $where[] = ['status', 'neq', "99"];
        if ($keyword) {
            $where[] = ['name', 'like', "%{$keyword}%"];
        }
        $page       = $this->request->param('page/d', 1);
        $limit      = $this->request->param('limit/d', 20);
        $order = 'tp.id';
        $systemUserKV = getSystemUserKV(null);
        $projectData = db('t_project tp')->where($where)
            ->join('t_project_user pro_user', "pro_user.project_id=tp.id and pro_user.type=1", 'left')->field('tp.*,pro_user.admin_id as audit_id')
            ->page($page)->limit($limit)->order($order)->select();
        $projectTaskCounts=db("t_task")->where([['project_id', 'in', array_column($projectData,'id')],['status','<',99]])
            ->group("project_id")->column("count(id) as all_count,sum(case when status=3 then 1 else 0 end) as finish_count","project_id");
        foreach ($projectData as $key => $value) {
            $projectUserList = $tProjectService->getUsersByProjectId($value['id']);
            $value['userAll'] = implode('、', array_values($projectUserList));
            $value['all_task_count']=isset($projectTaskCounts[$value['id']]) ? $projectTaskCounts[$value['id']]['all_count'] : 0;
            $value['finish_task_count']=isset($projectTaskCounts[$value['id']]) ? $projectTaskCounts[$value['id']]['finish_count'] : 0;
            $value['finish_task_per']=!empty($projectTaskCounts[$value['id']]['finish_count']) ? round($projectTaskCounts[$value['id']]['finish_count']/$projectTaskCounts[$value['id']]['all_count'] * 100,2) .'%' : "0.00%" ;
            $value['nick']=arrayGet($systemUserKV, $value['admin_id']);
            $value['audit_id_name']=arrayGet($systemUserKV, $value['audit_id']);
            $value['status']=$value['finish_task_count']==$value['all_task_count'] && $value['finish_task_count']>0 ? 3 : $value['finish_task_count']>0 ? 2 : 1 ;
            $data['rows'][]=$value;
        }
        $data['count'] = db('t_project')->where($where)->count('id');
        $this->return_json(200,$data);
    }


    /**
     * 任务列表
     * @return string
     */
    public function taskList(){
        $this->checkLogin();
        $projectId = $this->request->param('project_id/d', 0);
        $type = $this->request->param('type/d', 0);	// 0全部，1我创建，2我参与，3我关注,
        $order = $this->request->param('order/s', 'priority');	// 优先级，创建时间，更新时间
        $page       = $this->request->param('page/d', 1);
        $status     =$this->param('status',''); //0待审批,1未开始，2进行中，3已完成 4与我相关
        $limit      = $this->request->param('limit/d', 20);
        $user_process_id=$this->request->param('user_process_id/d', 0);
        $keywords=$this->param('keywords','');
        if($projectId<=0){
            $status=$type; $type=0;
        }


        $result = [];
        $where = [];
        $whereJoin = "1=1";
        $where[]=['status','<',99];
        if ($projectId) $where[] = ['project_id', '=', $projectId];
        $whereOR=[];
        if(!empty($keywords)){
            $whereOR[] = ['name', 'like', "%{$keywords}%"];
            $whereOR[] = ['client_ordernum', 'like', "%{$keywords}%"];
        }
        if(in_array($status,array(4))){  //与我相关 -->  待我审批,由我创建,由我协助,由我执行的任务
            $whereOR2[] = ['audit_uid', '=', $this->adminId];
            $whereOR2[] = ['admin_id', '=', $this->adminId];
            $whereOR2[] = ['execute_uid', '=', $this->adminId];
            $whereJoin = "FIND_IN_SET(".$this->adminId.", join_admin_ids)";
        }else{
            if ($status !=='') $where[] = ['status', '=', $status];
            if ($type == 1) $where[] = ['a.admin_id', '=', $this->adminId];
            if ($type == 2) {
                $where[] = ['a.admin_id', '<>', $this->adminId];
            } elseif ($type == 3) $where[] = ['id', 'in', db('t_task_attention')->where('admin_id', $this->adminId)->column('task_id')];
            if ($type == 4) $where[] = ['execute_uid', '=', $this->adminId];
        }
        if($user_process_id>0){  //自定义分组任务列表
            $where[] = ['id', 'in', db('t_task_user_process')->where([['admin_id','eq', $this->adminId],['user_process_id','eq',$user_process_id]])->column('task_id')];
        }
        $field = "id,name,client_ordernum,admin_id,project_id,material_id,material_sku,priority,status,audit_uid,audit_status,execute_uid,a.create_time,update_time";
        if(in_array($status,array(4))){
            if(!empty($keywords)){
                $whereOR2=[];
            }
            $datalist= db('t_task a')->whereOr($whereOR)->whereOr($whereOR2)->whereOr($whereJoin)->page($page)->limit($limit)->field($field)->order('create_time', 'desc')->select();
        }else{
            $datalist= db('t_task a')->whereOr($whereOR)->where($where)->page($page)->limit($limit)->field($field)->order('create_time', 'desc')->select();
        }
        $user_process_tasks=db('t_task_user_process')->where([['task_id', 'in', array_column($datalist,'id')],['admin_id','eq',$this->adminId]])->column('user_process_id','task_id');
        $comments=db('t_task_comment')->field("task_id,count(id) as count")->where([['task_id', 'in', array_column($datalist,'id')]])->group('task_id')->select();
        $userPicKV=$this->getUserHeadpicList(array_column($datalist,'admin_id'));
        $commentsArr=array_column($comments,'count','task_id');
        $systemUserKV = getSystemUserKV(null);
        $project_names=db("t_project")->where([['id', 'in', array_column($datalist,'project_id')]])->column('name,id','id');
        foreach ($datalist as $key=>&$val){
            $val['comments']= isset($commentsArr[$val['id']]) ? $commentsArr[$val['id']] : 0;
            $val['audit_user']=arrayGet($systemUserKV,$val['audit_uid'],'');
            $val['execute_user']=arrayGet($systemUserKV,$val['execute_uid'],'');
            $val['headimgurl']=isset($userPicKV[$val['admin_id']]) ? $userPicKV[$val['admin_id']] : '';
            $val['admin_user']=arrayGet($systemUserKV,$val['admin_id'],'');
            $val['user_process_id']=isset($user_process_tasks[$val['id']]) ? $user_process_tasks[$val['id']] : '';
            $val['project_name']=isset($project_names[$val['project_id']]) ? $project_names[$val['project_id']] : '' ;
        }
        $countWhere[] = ['audit_uid', '=', $this->adminId];
        $countWhere[] = ['admin_id', '=', $this->adminId];
        $countWhere[] = ['execute_uid', '=', $this->adminId];
        $countWhereJoin = "FIND_IN_SET(".$this->adminId.", join_admin_ids)";
        $countList=[
            db('t_task a')->where([['status', '=', 0]])->count(),db('t_task a')->where([['status', '=', 1]])->count(),
            db('t_task a')->where([['status', '=', 2]])->count(),
            db('t_task a')->where([['status', '=', 3]])->count(),
            db('t_task a')->whereOr($countWhere)->whereOr($countWhereJoin)->count()
        ];
        $result['rows'] =$datalist;
        $result['countarr']=$countList;
        $result['count'] = db('t_task a')->whereOr($whereOR)->where($where)->whereRaw($whereJoin)->count(1);
        $result['allTaskCount'] = db('t_task a')->where('status','<',99)->count(1);
        $this->return_json('200',$result);
    }

    /**
     * 任务新增功能
     */
    public function taskEdit(){
        $taskId= $this->request->param('task_id/d', 0);
        $projectId = $this->request->param('project_id/d', 0);
        $name = $this->request->param('name/s', '');
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $materialSku = $this->request->param('material_sku/s', '');
        $content = $this->request->param('content/s', '');
        $priority = $this->request->param('priority/d', 2);
        $execute_uid = $this->param('execute_uid/d');
        $join_admin_ids = $this->param('join_admin_ids/s');
        $orderQuantity = $this->param('order_quantity/d');
        $real_order_quantity = $this->request->param('real_order_quantity/d', '');
        $real_process_price = $this->request->param('real_process_price/s', '');
        $process_price=$this->param('process_price/s');
        $notic_open = $this->param('notice_open/d');
        $systemUserKV = getSystemUserKV(null);
        if(empty($name) || empty($execute_uid) || empty($projectId)){
            $this->return_json('401','项目id或任务名称或执行人参数缺失');
        }
        $orderService = new OrderService();
        if ($clientOrdernum != '') {
            //$oInfo = $orderService->getInfoByClientOrdernum($clientOrdernum, 'id');
//            if (empty($oInfo)) {
//                $this->return_json(401,'订单号不存在');
//            }
        }
        $this->checkLogin();
        try {
            db()->startTrans();
            $insData = [
                'project_id' => $projectId,
                'name' => $name,
                'client_ordernum' => $clientOrdernum,
                'material_sku' => $materialSku,
                'content' => $content,
                'execute_uid'=>$execute_uid,
                'priority' => $priority,
                'admin_id' => $this->adminId,
                'join_admin_ids' => $join_admin_ids,
                'order_quantity'=>$orderQuantity,
                //'process_price'=>$process_price,
                'material_id'=>$process_price,
                'real_order_quantity'=>$real_order_quantity,
                'real_process_price'=>$real_process_price,
                'status' => 0,
                'create_time' => time(),
                'update_time' => time(),
            ];
            $audit_uid= db('t_project_user')->where(['project_id'=>$projectId,'type'=>1])->value('admin_id', '0');//审批人
            if($notic_open==2){
                $insData['close_notice_uid']=$this->adminId;
            }
            if (empty($taskId)) {
                $insData['audit_uid'] = $audit_uid;
                $taskId = db('t_task')->insertGetId($insData);
                // 记录操作日志
                $this->addLog($projectId, $taskId, 3, '新建了任务', 0);
            } else {
                unset($insData['create_time']);
                unset($insData['admin_id']);
                unset($insData['status']);
                $oldtaskinfo = db('t_task')->find($taskId);
                db('t_task')->where('id', $taskId)->update($insData);
                if ($oldtaskinfo['name'] != $name) {
                    $content="原标题：". $oldtaskinfo['name'];
                    $this->addLog($projectId, $taskId, 1, '更新了任务标题', 0, $name,$content);
                }
                if ($oldtaskinfo['content'] != $content) {
                    $this->addLog($projectId, $taskId, 1, '更新了任务描述', 0, '原描述：'.$oldtaskinfo['content']);
                }
                if ($oldtaskinfo['priority'] != $priority) {
                    $this->addLog($projectId, $taskId, 1, '更新了任务 重要性' . $oldtaskinfo['priority'] . '->' . $priority, 0);
                }
                if ($oldtaskinfo['execute_uid'] != $execute_uid) {
                    $oldExeName = arrayGet($systemUserKV, $oldtaskinfo['execute_uid'], '');
                    $newExeName = arrayGet($systemUserKV, $execute_uid, '');
                    $this->addLog($projectId, $taskId, 1, '将任务指派给' . $newExeName . '，原指派人： ' . $oldExeName, 0);
                }
            }
            db()->commit();
            $retData['task_id']=$taskId;
            $this->return_json(200,$retData);
        } catch (\Exception $e) {
            db()->rollback();
            $this->return_json(501, "操作失败，". $e->getMessage(). $e->getLine());
        }
    }

    //审核任务
    public function checkTask(){
        $taskId=$this->param('task_id');
        $audit_status=$this->param('audit_status');
        $taskInfo=db('t_task')->where('id',$taskId)->find();
        $this->checkLogin();
        $audit_users=db('t_project_user')->where([['project_id','eq',$taskInfo['project_id']],['type','eq',1]])->column("admin_id");
        if(empty($taskInfo)){
            $this->return_json(401,'不存在的任务id');
        }
        if(!in_array($audit_status,array(1,2))){
            $this->return_json(401,'错误的审批状态');
        }
        if($taskInfo['audit_status']!=0){
            //$this->return_json(401,'该任务已审核');
        }
        if(!in_array($this->adminId,$audit_users)){
            $this->return_json(403,'你无权限审批该任务');
        }
        $audits=['','通过','驳回'];
        $savedata=['audit_status'=>$audit_status];
        $remark='审批了任务'.$audits[$audit_status];
        $progreccid=0;
        if($audit_status==1){
            $savedata['status']=1;
            $remark.='，任务状态已变更为未开始';
            $progreccid=1;
        }
        db('t_task')->where('id',$taskId)->update($savedata);
        $this->addLog($taskInfo['project_id'],$taskId, 3, $remark,0,'',$progreccid);
        $retData['task_id']=$taskId;
        $this->return_json(200,$retData);
    }

    //设置任务进度
    public function  setTaskStatus(){
        $taskId=$this->param('task_id');
        $status=$this->param('status');
        $task_user_process_id=$this->param('user_process_id/d',0);
        $taskInfo=db('t_task')->where('id',$taskId)->find();
        $this->checkLogin();
        if(empty($taskInfo)){
            $this->return_json(401,'不存在的任务id');
        }
        if(!in_array($status,array(0,1,2,3))){
            $this->return_json(401,'错误的任务进度值status');
        }
        if($taskInfo['status']==0 && $status>0){
            //$this->return_json(401,'未审批的任务不能调整到其它进度里');
        }
        if($taskInfo['status']>0 && $status==0){
            $this->return_json(401,'已经审批的任务不能调回待审批');
        }
        if($task_user_process_id>0){
            $userProcessinfo=db('t_user_process')->where('admin_id',$this->adminId)->find($task_user_process_id);
            if(empty($userProcessinfo)){
                $this->return_json(403,'未找到对应的任务自定义列表');
            }
            $status=$userProcessinfo['process_state'];
            db("t_task_user_process")->where('task_id',$taskId)->delete();
            $insData=['user_process_id'=>$task_user_process_id,'task_id'=>$taskId,'admin_id'=>$this->adminId,'create_time'=>time()];
            $task_user_process_id = db('t_task_user_process')->insertGetId($insData);
        }
        $task_status=['未审批','未开始','进行中','已完成'];
        $savedata=['status'=>$status];
        $remark='将任务移动到 '.$task_status[$status];
        if($taskInfo['status']!=$status){
            db('t_task')->where('id',$taskId)->update($savedata);
            $logid=$this->addLog($taskInfo['project_id'],$taskId, 3, $remark,0,'',$status);
            if(!empty($logid)){
                db('t_task_log')->where('id',$logid)->update(['progress_id'=>$status]); //设置进度值 以供统计
            }
        }

        $retData['task_id']=$taskId;
        $this->return_json(200,$retData);
    }

    //增加自定议任务分类列表
    public function userProcessEdit(){
        $processId=$this->param('user_process_id/d', '');
        $process_state=$this->param('process_state/d', '');
        $process_name=$this->param('process_name');
        $sort=$this->param('sort/d',50);
        if($process_name=='' || !in_array($process_state,[0,1,2,3])){
            $this->return_json(403,'自定义列表名称或列表所属任务进度状态值异常');
        }
        $insData=[
            'process_state'=>$process_state,
            'process_name'=>$process_name,
            'sort'=>$sort,
            'admin_id'=>$this->adminId,
            'create_time'=>time()
        ];
        if(!empty($processId)){
            $oldUserProcessinfo=db('t_user_process')->find($processId);
            if($oldUserProcessinfo['admin_id']!=$this->adminId){
                $this->return_json(403,'您无权限修改该任务自定义分类');
            }
            db('t_user_process')->where('id',$processId)->update($insData);
            $userProcessId=$processId;
        }else{
            $userProcessId = db('t_user_process')->insertGetId($insData);
        }
        $this->return_json(200,['user_process_id'=>$userProcessId]);
    }

    //获取自定义任务分类
    public function getUserProcesses(){
        $userProcessList=db("t_user_process")->where('admin_id','eq',$this->adminId)->order("sort desc,id desc")->select();
        $this->return_json(200,['rows'=>$userProcessList]);
    }

    //删除自定义任务列表
    public function setUserProcessDel(){
        $processId=$this->param('user_process_id/d', '');
        if(!empty($processId)){
            $userProcessinfo=db('t_user_process')->find($processId);
            if($userProcessinfo['admin_id']!=$this->adminId){
                $this->return_json(403,'您无权限删除该任务自定义分类');
            }
            db('t_user_process')->where('id',$processId)->delete();
            db('t_task_user_process')->where([['admin_id','eq',$this->adminId],['user_process_id','eq',$processId]])->delete();
        }else{
            $this->return_json(401,'自定义任务列表id缺失');
        }
        $this->return_json(200);
    }

    //删除项目
    public function setPorjectDel(){
        $this->checkLogin();
        $projecid=$this->param('projectid');
        $projectinfo=db('t_project')->where('id',$projecid)->find();
        if(empty($projectinfo)){
            $this->return_json(401,'不存在的项目id');
        }
        $proTaskInfo=db('t_task')->where([['project_id','eq',$projecid],['status','<','99']])->find();
        if(!empty($proTaskInfo)){
            $this->return_json(401,'该项目还存在任务，请先删除任务再删除项目');
        }
        if($projectinfo['admin_id']!=$this->adminId){
            $this->return_json(403,'只有创建者才能删除该项目');
        }
        db('t_project')->where('id',$projecid)->update(['status'=>'99']);
        $this->return_json(200);
    }

    //设置任务删除
    public function setTaskDelete(){
        $this->checkLogin();
        $taskId=$this->param('task_id');
        $taskInfo=db('t_task')->where('id',$taskId)->find();
        if(empty($taskInfo)){
            $this->return_json(401,'不存在的任务id');
        }
        $audit_uid= db('t_project_user')->where(['project_id'=>$taskInfo['project_id'],'type'=>1])->value('admin_id', '0');//项目的负责人
        if($audit_uid!=$this->adminId && $taskInfo['admin_id']!=$this->adminId){
            $this->return_json(403,'只有审批人或创建人才能删除该任务');
        }
        db('t_task')->where('id',$taskId)->delete();//update(['status'=>'99']);
        $this->return_json(200);
    }


    public function getTaskInfo(){
        $systemUserService=new SystemUserService();
        $systemUserVK = $systemUserService->getKVList(null);
        $taskId=$this->param('task_id');
        $taskInfo=db('t_task')->where('id',$taskId)->find();
        $this->checkLogin();
        if(empty($taskInfo)){
            $this->return_json(401,'不存在的任务id');
        }else{
            $taskInfo['notice_open']=strpos(','.$taskInfo['close_notice_uid'].',',chr($this->adminId))===false ? 1 : 2;
            $task_annex_list=db("t_task_annex")->where('task_id', $taskId)->field('id,admin_id,name,path,create_time')->select();

            $result = array();
            $result=explode(',',$taskInfo['join_admin_ids']);
            $atAdminIds=[];
            foreach ($result as $key => $value) {
                $atAdminIds[]= arrayGet($systemUserVK, $value, '');
            }
            $atAdminIds = implode(" , ", $atAdminIds);
            $taskInfo['join_admins']=$atAdminIds;
            $taskInfo['task_annex_list']=$task_annex_list;
            $this->return_json(200,$taskInfo);
        }
    }

    //获取订单物料列表
    public function getOrderMaterials(){
        $orderNumbers = $this->request->param('client_ordernum/s', '');
        $orderNumbers=trim($orderNumbers);
        $orderNumbers=explode(',',str_replace(["，",'/'],",",$orderNumbers));
        $result=db('order_material om')->join('material m', "om.material_id=m.id", 'left')
            ->where([['client_ordernum','in',$orderNumbers]])->field('om.mid,om.material_id,om.order_id,om.client_ordernum,om.fabric_width,om.weight
                ,om.material_dosage,om.loss,om.caigou_status,om.factory_id
                ,om.is_make_tag,om.is_caigou_start,om.need_checkcloth,om.need_shrink
                ,om.caigou_unitprice,om.shiji_caigou_count,om.tiaoshu,om.tiaoshu_detail,om.tiaoshu_status,om.return_length
                ,om.arrive_time,om.arrive_time_first,om.caigou_over_time
                ,om.send_goods_status,om.create_time,om.need_num
                ,m.pic,m.name,m.type,m.material_sku,m.model,m.colornum,m.color,m.supplier,m.address,m.contact
                ,m.purchasing_unit')->select();
        $orderMaterials=[];
        foreach($result as $key=>$item){
            $materialtype=$item['type']=='accessories' ? '[辅]' : '[面]';
            $item['detail']="名称:$item[name],供应商:$item[supplier],颜色:$item[color],色号:$item[colornum],型号:$item[model]";
            $item['name']=$materialtype.$item['name'];
            $orderMaterials[]=$item;
        }
        $ret['rows']=$orderMaterials;
        $ret['count']=count($result);
        $this->return_json(200,$ret);
    }

    //获取任务评论列表
    public function getTaskCommentList(){
        $taskId=$this->param('task_id');
        $systemUserKV = getSystemUserKV(null);
        $page       = $this->request->param('page/d', 1);
        $limit      = $this->request->param('limit/d', 20);
        $commentList=db('t_task_comment')->where('task_id', $taskId)->page($page)->limit($limit)->order('update_time desc')->where('status', 1)->select();
        if(!empty($commentList)) {

        }
        $userPicKV=$this->getUserHeadpicList(array_column($commentList,'admin_id'));
        foreach ($commentList as $key => &$value) {
            $a=str_replace('&lt;','<',$value['content']);
            $b=str_replace('&gt;','>',$a);
            $c=str_replace('&quot;','"',$b);
            $d=str_replace('nbsp;','',$c);
            $e=str_replace('&amp;',' ',$d);
            $value['content']=$e;
            $value['realname']= arrayGet($systemUserKV,$value['admin_id'],'');
            $value['headimgurl']=isset($userPicKV[$value['admin_id']])?$userPicKV[$value['admin_id']] : '';
        }
        $ret['rows']=$commentList;
        $ret['count']=db('t_task_comment')->where('task_id', $taskId)->where('status', 1)->count();
        $this->return_json(200,$ret);
    }

    //增加评论
    public function commentAdd(){
        $taskId = $this->request->param('task_id/d', 0);
        $content = $this->request->param('content/s', '');
        $tTaskService = new TTaskService();
        $this->checkLogin();
        $ttInfo = $tTaskService->getInfoById($taskId);
        if (empty($taskId) || empty($content)) {
            $this->return_json(401,'必填字段不能为空');
        }
        if (empty($ttInfo) || empty($content)) {
            $this->return_json(401,'任务不存在');
        }
        //新增评论
        try {
            db()->startTrans();
            $CommentData=[
                'project_id' => $ttInfo['project_id'],
                'task_id' => $ttInfo['id'],
                'content' => $content,
                'admin_id' => $this->adminId,
                'create_time' => time(),
                'update_time' => time(),
            ];
            $commentId = db('t_task_comment')->insertGetId($CommentData);
            //更新任务时间
            db('t_task')->where('id',$ttInfo['id'])->update(['update_time'=>time()]);
            // 记录操作日志
            $this->addLog($ttInfo['project_id'],$ttInfo['id'], 2, '新增了任务评论',$commentId);
            db()->commit();
            $this->return_json(200,['commentid'=>$commentId]);
        } catch (\Exception $e) {
            db()->rollback();
            $this->return_json(501, "操作失败，". $e->getMessage());
        }
    }

    //获取任务的日志列表
    public function getTaskLogList(){
        $taskId=$this->param('task_id');
        $systemUserKV = getSystemUserKV(null);
        $page       = $this->request->param('page/d', 1);
        $limit      = $this->request->param('limit/d', 20);
        $this->checkLogin();
        $logList=db('t_task_log')->where('task_id', $taskId)->page($page)->limit($limit)->order('create_time asc')->select();
        if(empty($logList)) {
            $this->return_json(200, ['rows'=>[],'count'=>0]);
        }
        $userPicKV=$this->getUserHeadpicList(array_column($logList,'admin_id'));
        foreach ($logList as $key => &$value) {
            $value['realname']= arrayGet($systemUserKV,$value['admin_id'],'');
            $value['headimgurl']=isset($userPicKV[$value['admin_id']])?$userPicKV[$value['admin_id']] : '';
        }
        $ret['rows']=$logList;
        $ret['count']=db('t_task_log')->where('task_id', $taskId)->count();
        $this->return_json(200,$ret);
    }

    //获取成员头像
    private function getUserHeadpicList($adminArr){
        $userPicList=db('wechat_user')->where([['admin_id','in',$adminArr]])->column("admin_id,headimgurl",'admin_id');
        //$userPicKV=array_column($userPicList,'headimgurl','admin_id');
        return $userPicList;
    }


    /**
     *增加任务日志
     * @logType //1任务修改 2评论, 3其它包括指派/改变进度/完成状态等
    */
    public function addLog($projectId,$taskId,$logType,$remark,$commentId=0,$content='',$progressId=0) {
        $logInfo=[
            'project_id' => $projectId,
            'task_id' => $taskId,
            'comment_id' => $commentId,
            'type' => $logType,//1指派任务及修改 2评论, 3改变进度状态的日志
            'remark' => $remark,
            'content'=>$content,
            'progress_id'=>$progressId,
            'admin_id' => $this->adminId,
            'create_time' => time(),
        ];
        return db('t_task_log')->insertGetId($logInfo);
    }

    //返回任务流程信息
    public function getTaskProcessList(){

    }

    //附件上传功能
    public function annexUpload(){
        $projectid=$this->param('projectid',0);
        $taskId=$this->param('task_id',0);
        $this->checkLogin();
        $upload = AnnexModel::fileUpload(['group' => 'temp', 'driver' => 'local','thumb'=>'no']);
        $this->adminId=0;
        if (isset($upload['data']['file'])) {
            $uploadinfo=$upload['data'];
            $filePath = $upload['data']['file'];
            $insertData=['project_id'=>$projectid,'task_id'=>$taskId,'admin_id'=>$this->adminId,'path'=>$uploadinfo['file'],'name'=>$uploadinfo['upfileName'],'create_time'=>time()];
            $insertid=db("t_task_annex")->insertGetId($insertData);
            $retdata=['filepath'=>$filePath,'filename'=>$insertData['name'],'annex_id'=>$insertid];
            $this->return_json(200,$retdata);
        } else {
            $this->return_json(401, $upload);
        }
    }

    /**
     * 项目新增功能
     */
    public function projectAdd(){
        $name = $this->request->param('name/s', '');
        $remark = $this->request->param('remark/s', '');
        $projectid=$this->param('projectid');
        $review_id=$this->param('review_id');
        $manager_ids=$this->param('manager_ids');
        $user_ids=$this->param('user_ids');
        $starttime=$this->param('starttime','0');
        $endtime=$this->param('endtime','0');
        $starttime=$starttime>0? strtotime($starttime) : 0;
        $endtime=$endtime>0 ? strtotime($starttime) : 0;
        $this->checkLogin();
        $systemUserKV = getSystemUserKV(null);
        if((empty($name) && empty($projectid)) || (empty($review_id) && empty($projectid))){
            $this->return_json('401','项目名称及负责人参数不能为空');
        }
        $projectData=[
            'name'=>$name,
            'remark'=>$remark,
            'start_time'=> $starttime,
            'end_time'=>$endtime,
            'create_time' => time(),
            'update_time' => time(),
            'admin_id'=>$this->adminId,
        ];
        if(empty($projectData['name'])) unset($projectData['name']);
        if(empty($projectData['remark'])) unset($projectData['remark']);
        db()->startTrans();
        if(!empty($projectid)){
            $oldProInfo=db('t_project')->find($projectid);
            $old_review_id=db('t_project_user')->where([['project_id','=',$projectid],['type','=',1]])->value('admin_id', '');
            if($oldProInfo['name']!=$name){
                $this->addLog($projectid,0, 1, '更新了项目标题',0,$name);
            }
            if($oldProInfo['remark']!=$remark){
                $this->addLog($projectid,0, 1, '更新了项目描述',0,$remark);
            }
            if($old_review_id!=$review_id){
                $oldExeName= arrayGet($systemUserKV,$old_review_id,'');
                $newExeName= arrayGet($systemUserKV,$review_id,'');
                $this->addLog($projectid,0, 1, '更新了项目负责人'.$newExeName.'，原负责人： '.$oldExeName,0);
            }
            db('t_project')->where('id',$projectid)->update($projectData);
        }else{
            $projectid= db('t_project')->insertGetId($projectData);
            $this->addLog($projectid,0, 1, '创建了项目',0,$name);
        }
        db('t_project_user')->where([['project_id','=',$projectid],['type','=',1]])->delete();
        $projectUserData=[
            'project_id'=>$projectid, 'admin_id'=>$review_id, 'type'=>1,
            'create_time' => time(), 'update_time' => time(),
        ];
        db('t_project_user')->insert($projectUserData);
        if($manager_ids){ //设置项目协助人
            db('t_project_user')->where([['project_id','=',$projectid],['type','=',2]])->delete();
            $manager_ids_arr=explode(',',$manager_ids);
            foreach ($manager_ids_arr as $manager_id) {
                $projectUserData=[
                    'project_id'=>$projectid, 'admin_id'=>$manager_id, 'type'=>2,
                    'create_time' => time(), 'update_time' => time(),
                ];
                db('t_project_user')->insert($projectUserData);
            }
            $user_pics=db('t_project_user proj_user')->join('wechat_user user', 'proj_user.admin_id = user.admin_id','left')->distinct("proj_user.admin_id")
                ->field('proj_user.admin_id,user.headimgurl')->where([['headimgurl','neq',''],['project_id','=',$projectid],['type','in',[1,2,3]]])->column("headimgurl");
            $user_pics=empty($user_pics) ? ['./static/wechat/default_header.png'] : $user_pics;
            $annexmodel=new AnnexModel();
            $projectGroupPic="./upload/image/".date("Ym")."/".md5($projectid).".jpg";
            $isupload = $annexmodel->getGroupAvatar($user_pics,1,$projectGroupPic);
            if($isupload){
                db('t_project')->where('id',$projectid)->update(['members_pic'=>substr($projectGroupPic,1)]);
            }
        }
        db()->commit();
        if($user_ids){ //编辑项目成员
            db('t_project_user')->where([['project_id','=',$projectid],['type','=',3]])->delete();
            $user_ids_arr=explode(',',$user_ids);
            foreach ($user_ids_arr as $manager_id) {
                $projectUserData=[
                    'project_id'=>$projectid, 'admin_id'=>$manager_id, 'type'=>3,
                    'create_time' => time(), 'update_time' => time(),
                ];
                db('t_project_user')->insert($projectUserData);
            }
        }
        $retData['projectid']=$projectid;
        return $this->return_json(200,$retData);

    }

    //获取项目详情
    public function getProjectInfo(){
        $projectid=$this->param('projectid');
        if (empty($projectid)) {
            $this->return_json(401,'projectid缺失');
        }
        $projectInfo=db('t_project')->find($projectid);
        //负责人
        $reviewUser=db('t_project_user proj_user')->join('system_user user', 'proj_user.admin_id = user.id','left')
            ->field('user.nick,proj_user.admin_id')->where([['project_id','=',$projectid],['type','=',1]])->find();
        //协助人
        $projectManager=db('t_project_user proj_user')->join('system_user user', 'proj_user.admin_id = user.id','left')
            ->field('user.nick,proj_user.admin_id')->where([['project_id','=',$projectid],['type','=',2]])->select();
        //项目组成员
        $projectUser=db('t_project_user proj_user')->join('system_user user', 'proj_user.admin_id = user.id','left')
            ->field('user.nick,proj_user.admin_id')->where([['project_id','=',$projectid],['type','=',3]])->select();
        $projectInfo['reviewUser']=$reviewUser;
        $projectInfo['project_manager']=$projectManager;
        $projectInfo['project_user']=$projectUser;
        return $this->return_json(200,$projectInfo);
    }

    /**
     * @throws \think\Exception
     * 项目日志列表
     */
    public function getProgectLogList(){
        $projectid=$this->param('projectid');
        $systemUserKV = getSystemUserKV(null);
        $page       = $this->request->param('page/d', 1);
        $limit      = $this->request->param('limit/d', 20);
        if (empty($projectid)) {
            $this->return_json(401,'projectid缺失');
        }
        $this->checkLogin();
        $logList=db('t_task_log')->where([['project_id','eq',$projectid],['task_id','eq','0']])->page($page)->limit($limit)->order('create_time desc')->select();
        if(empty($logList)) {
            $this->return_json(200, ['rows'=>[],'count'=>0]);
        }
        $userPicKV=$this->getUserHeadpicList(array_column($logList,'admin_id'));
        foreach ($logList as $key => &$value) {
            $value['realname']= arrayGet($systemUserKV,$value['admin_id'],'');
            $value['headimgurl']=isset($userPicKV[$value['admin_id']])?$userPicKV[$value['admin_id']] : '';
        }
        $ret['rows']=$logList;
        $ret['count']=db('t_task_log')->where([['project_id','eq',$projectid],['task_id','eq','0']])->count();
        $this->return_json(200,$ret);
    }

    //获取项目进展统计数据
    public function getProjectTaskProcessCountsList(){
        //0待审批，1未开始，2进行中，3已完成
        $projectid=$this->param('projectid');
        $startTime=$this->param('start_time');
        $endTime=$this->param('end_time');
        $where =[['project_id','eq',$projectid],['type','eq','3']];
        if(!empty($startTime) && !empty($endTime)){
            $timelimits=strtotime($startTime." 00:00:00").",".strtotime($endTime." 23:59:59");
            $where[]=['create_time','between',$timelimits];
        }
        $taskTypeCountList=db('t_task_log')->field("FROM_UNIXTIME(create_time,'%Y-%m-%d') as day,count(id) as count,type,progress_id")
            ->where($where)->group("progress_id,FROM_UNIXTIME(create_time,'%Y-%m-%d')")->order('create_time asc')->select();
        $projectProcessCounts=db('t_task_log')->field("count(id) as count,progress_id")
            ->where($where)->group("progress_id")->select();
        $retArr=array();
        foreach ($taskTypeCountList as $key=>$countval){
            $retArr[$countval['day']][]=$countval;
        }
        $this->return_json(200,array('rows'=>$retArr,'projectProcessCounts'=>$projectProcessCounts,'projectTaskCounts'=>array_sum(array_column($projectProcessCounts,'count'))));
    }

    //获取用户列表
    public function getTaskUsers(){
        $projectid = $this->request->param('projectid/d', 0);
        $this->checkLogin();
        $user_mod=db('system_user user')->where([['status','=',1]])
            ->field('user.nick,user.id');
        if($projectid){
            $user_mod->join('t_project_user proj_user', 'proj_user.admin_id = user.id','left')->where([['project_id','=',$projectid]]);
        }
        $userlist=$user_mod->select();
        return $this->return_json(200,$userlist);
    }

    //个人所有项目任务完成情况
    public function getUserTaskProcessCounts(){
        $this->checkLogin();
        $projectProcessCounts=db('t_task_log')->field("progress_id,project_id,count(id) as count")
            ->where([['admin_id','eq',$this->adminId],['type','eq','3']])->group("progress_id,project_id")->select();
        $project_names=db("t_project")->where([['id', 'in', array_column($projectProcessCounts,'project_id')]])->column('name,id','id');
        $resultCounts=[];
        foreach ($projectProcessCounts as $key=>&$val) {
            $val['project_name'] = isset($project_names[$val['project_id']]) ? $project_names[$val['project_id']] : '';
            $resultCounts[$val['progress_id']][]=$val;
        }
        return $this->return_json(200,$resultCounts);
    }

    //任务完成情况趋势
    public function getUserDayTaskProcessCounts(){
        $this->checkLogin();
        $dayTaskCountList=db('t_task_log')->field("FROM_UNIXTIME(create_time,'%Y-%m-%d') as day,count(id) as count,progress_id")
            ->where([['admin_id','eq',$this->adminId],['type','eq','3']])->group("FROM_UNIXTIME(create_time,'%Y-%m-%d')")->order('create_time asc')->select();
        return $this->return_json(200,$dayTaskCountList);
    }

    //获取消息通知列表
    public function getUserTaskMessageList(){
        $page       = $this->request->param('page/d', 1);
        $limit      = $this->request->param('limit/d', 50);
        $this->checkLogin();
        $systemUserKV = getSystemUserKV(null);
        $whereOr[] = ['admin_id|execute_uid|audit_uid','eq',$this->adminId];
        $whereOr[] = ['', 'exp', db()->raw("FIND_IN_SET({$this->adminId},join_admin_ids)")];
        //需要关注的task_id列表
        $task_ids=db('t_task')->whereOr($whereOr)->column('id','id');
        $task_ids[]=0;
        if(count($task_ids)>0){

        }
        $MsgWhere[]=['a.task_id','in',$task_ids];
        $MsgWhere[]=['a.admin_id','<>',$this->adminId];
        $MsgWhere[]=['a.task_id','gt',0];
        $task_ids_str=implode(',',$task_ids);
        $messageList=db("t_task_log a")->where($MsgWhere)->field("a.*,case when msg.is_read is null then 0 else msg.is_read end as is_read")
            ->join('t_task_message msg', 'a.id = msg.task_log_id and msg.task_id in ('.$task_ids_str.') and msg.admin_id='.$this->adminId,'left')
            ->page($page)->limit($limit)->order('a.create_time desc')->select();
        $task_names=db("t_task")->where([['id', 'in', $task_ids]])->column('name,id','id');
        foreach ($messageList as $key=>&$val) {
            $val['task_name'] = isset($task_names[$val['task_id']]) ? $task_names[$val['task_id']] : '';
            $val['admin_name']= arrayGet($systemUserKV,$val['admin_id'],'');
            $val['remark']=$val['admin_name'].$val['remark'];
        }
        $notreadCount=db("t_task_log a")->where($MsgWhere)->where('msg.is_read is null')->field("a.*")
            ->join('t_task_message msg', 'a.id = msg.task_log_id and msg.task_id in ('.$task_ids_str.') and msg.admin_id='.$this->adminId,'left')->count();
        $messageCount=db("t_task_log a")->where($MsgWhere)->field("a.*,case when msg.is_read is null then 0 else msg.is_read end as is_read")
            ->join('t_task_message msg', 'a.id = msg.task_log_id and msg.task_id in ('.$task_ids_str.') and msg.admin_id='.$this->adminId,'left')->count();
        $this->return_json(200,['rows'=>$messageList,'count'=>$messageCount,'not_read_count'=>$notreadCount]);

    }

    //获取消息详情
    public function getUserTaskMessageInfo(){
        $logid = $this->request->param('log_id', '');
        if(empty($logid)) {
            $this->return_json(401, '参数消息id缺失');
        }
        $this->checkLogin();
        $systemUserKV = getSystemUserKV(null);
        $messageInfo=db("t_task_log a")->where([['a.id','eq',$logid]])->field("a.*,msg.is_read")
            ->join('t_task_message msg', 'a.id = msg.task_log_id and msg.admin_id='.$this->adminId,'left')->find();
        if(is_null($messageInfo['is_read'])){
            $readdata=['project_id'=>$messageInfo['project_id'],'task_id'=>$messageInfo['task_id'],'task_log_id'=>$messageInfo['id'],
                'type'=>$messageInfo['type'],'admin_id'=>$this->adminId,'is_read'=>1,'create_time'=>time()];
            $insertid=db("t_task_message")->insertGetId($readdata);
            $messageInfo['is_read']=0;
        }

        $task_names=db("t_task")->where([['id', 'in', $messageInfo['task_id']]])->find();
        $messageInfo['task_name'] = isset($task_names['name']) ? $task_names['name'] : '';
        $messageInfo['admin_name']= arrayGet($systemUserKV,$messageInfo['admin_id'],'');
        $this->return_json(200,$messageInfo);
    }

    /*
     * 绑定帐号
     */
    public function bindMimoAccount(){
        $model = new UserModel;
        $code=$this->param('code');
        $username=$this->param('mimo_username');
        $password=$this->param('password');
        if($code){
            $uid = $model->login($username, $password,true);
            if ($uid) {
                $wechatOauth = \We::WeMiniCrypt(config('wechat.'));
                $wechatdata=$wechatOauth->session($code);
                if (isset($wechatdata['errcode'])) {
                    $this->return_json('401',$wechatdata['errmsg']);
                }
                $weixin_unionid=$wechatdata['openid'];
                $wechatUserInfo = (new WechatUser())->getInfoByUnionid($weixin_unionid);
                if (!$wechatUserInfo) {
                    $insData = [
                        'weixin_unionid' => $weixin_unionid,
                        'admin_id'=>$uid,
                        'subscribe' => 0,
                        'create_time' => time(),
                        'update_time' => time(),
                    ];
                    $insertid=db('wechat_user')->insertGetId($insData);
                    $wechatUserInfo['admin_id']=$uid;
                    $wechatUserInfo['id']=$insertid;
                } else {
                    $upData = [
                        'admin_id'=>$uid,
                        'update_time' => time(),
                    ];
                    db('wechat_user')->where('id', $wechatUserInfo['id'])->update($upData);
                }
                $userInfo=(new WechatUser())->getInfoByUnionid($weixin_unionid);
                $userInfo['realname'] = db('system_user')->where('id', $wechatUserInfo['admin_id'])->value('nick', '');
                $this->setSessionKey($userInfo);
                $ret=['admin_id'=>$wechatUserInfo['admin_id'],'msg'=>'绑定成功'];
                $this->return_json(200,$ret);

            }else{
                $this->return_json('401',$model->getError());
            }
        }else{
            $this->return_json(403,'没有传递code');
        }
    }

    //判断登录
    private function checkLogin(){
        if(empty($this->adminId)){
            $this->return_json(301,'未检测到帐号绑定信息，请先绑定帐号，或检查header头帐号信息是否传递');
        }
    }

    /**
     * 小程序授权登录
     */
    public function autoLogin(){
        parent::autoLogin();
    }

    /**
     * 获取用户登录信息
     */
    public function userinfo(){
        $sessionUser=$this->loginUser;
        if(empty($sessionUser)){
            $this->return_json(403,'没有传递或错误的用户session');
        }
        $userinfo=db('wechat_user')->field('nickname,sex,province,city,country,headimgurl,admin_id')->where('id', $sessionUser['wechat_user_id'])->findOrEmpty();
        if(empty($userinfo)){
            $this->return_json(403,'没有传递或错误的用户session');
        }
        $userinfo['realname'] = db('system_user')->where('id', $userinfo['admin_id'])->value('nick', '');
        $this->return_json(200,$userinfo);
    }
}